package com.amtf.datafile2.core.txt;

import java.io.File;
import java.util.List;

import com.amtf.common.Util;
import com.amtf.datafile2.DataException;
import com.amtf.datafile2.cfg.txt.TxtDataFieldDefinition;
import com.amtf.datafile2.cfg.txt.TxtDataTableDefinition;
import com.amtf.datafile2.cfg.txt.TxtDataTableDefinitionStore;
import com.amtf.datafile2.core.std.StdDataCatalog;

public class TxtDataCatalog extends StdDataCatalog<TxtDataTable, TxtDataTableDefinition, TxtDataFieldDefinition> {
	// public static enum ACCESS_TYPE {
	// READ, WRITE, APPEND_WRITE, READ_AND_WRITE, READ_AND_APPEND_WRITE;
	// }

	private String defaultEncoding = "UTF-8";
	private File dir = null;

	public TxtDataCatalog(String name, File file, String charsetName) throws DataException {
		this(name, file, "", false, charsetName);
	}

	public TxtDataCatalog(String name, File dirOrFile, String targetFilePattern, boolean subFolder, String charsetName) throws DataException {
		super(name);
		this.defaultEncoding = charsetName;

		if (!dirOrFile.exists() || dirOrFile.isFile()) {
			this.dir = dirOrFile.getParentFile();
			TxtDataTable dt = new TxtDataTable(dirOrFile.getName(), dirOrFile, charsetName, TxtDataTableDefinitionStore.UTF8_CSV_WITH_TITLE.clone());
			setDataTable(dt.getName(), dt);
		} else if (dirOrFile.isDirectory()) {
			this.dir = dirOrFile;

			List<File> files = Util.fsFindFiles(dirOrFile.getPath(), targetFilePattern, subFolder);
			for (File file : files) {
				TxtDataTable dt = new TxtDataTable(file.getName(), file, charsetName, TxtDataTableDefinitionStore.UTF8_CSV_WITH_TITLE.clone());
				setDataTable(dt.getName(), dt);
			}
		}
	}

	private File getDataTableFile(String name) {
		String newfile = dir.getPath() + File.separator + name;
		return new File(newfile);
	}

	public TxtDataTable createDataTable(String name, TxtDataTableDefinition definition) throws DataException {
		if (this.isDataTableExists(name) && getDataTableFile(name).length() != 0) {
			throw new DataException("Data table exist!");
		}

		TxtDataTable dt = null;
		dt = new TxtDataTable(name, getDataTableFile(name), defaultEncoding, definition);

		setDataTable(dt.getName(), dt);
		return dt;
	}

	@Override
	public TxtDataTable dropDataTable(String name) throws DataException {
		TxtDataTable dt = getDataTable(name);
		if (dt != null) {
			dt.close();
			getDataTableFile(name).delete();
		}

		return super.dropDataTable(name);
	}

}
